module Main where

import AI
import Evaluator2
import GameLoop

import System.Environment
import System.IO
import System.Random

import Data.Char
import Data.Maybe
import Control.Monad


data Player = Player1 | Player2

-- точка входа в бота, сейчас он управляется stupid_ai
current_ai = alpha_ai

main = do
  setStdGen $ mkStdGen 0
  hSetBuffering stdin LineBuffering
  hSetBuffering stdout LineBuffering

  p <- getArgs
  let player = fromMaybe (error "can't get player") $ lookup (take 1 p) [(["0"], Player1),(["1"], Player2)]

  case player of
    Player1 -> player1_loop current_ai init_game_state 1 []
    Player2 -> player2_loop current_ai init_game_state 1 []

player1_loop ai state k opp_turns = do
  turn <- ai state k opp_turns
  putStr $ show_turn turn
  let (res, state') = apply turn state

  let state'' = swap_players state'
  opp_turn <- read_turn
  let (_, state''') = apply opp_turn state''

  player1_loop ai (swap_players state''') (k+1) (opp_turn : opp_turns)

player2_loop ai state k opp_turns = do
  opp_turn <- read_turn
  let (_, state') = apply opp_turn state

  let state'' = swap_players state'
  let opp_turns' = opp_turn : opp_turns
  turn <- ai state'' k opp_turns'
  putStr $ show_turn turn
  let (res, state''') = apply turn state''

  player2_loop ai (swap_players state''') (k+1) opp_turns'


-- сериализация
show_turn (LeftApp s n) = unlines ["1", show_card s, show n]
show_turn (RightApp n s) = unlines ["2", show n, show_card s]

show_card c = let str = show c
              in if length str > 1 then lower str else str

lower = map toLower
-- десериализация
read_turn = do
  lns <- sequence (replicate 3 getLine)
  return $ parse_turn lns

cards_str = map (map toLower . show) cards

cards_list = zip cards_str cards

parse_turn lns = let [dir, a, b] = lns
                 in if dir == "1" then LeftApp (parse_card a) (parse_slot b)
                     else RightApp (parse_slot a) (parse_card b)

parse_card c = fromMaybe (error $ "can't parse card " ++ c) $ lookup (lower c) cards_list

parse_slot :: String -> Int
parse_slot s = read s
